package com.jack.leetcode.每日一题;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和 {

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> result = threeSum(nums);
        result.forEach(r->{
            r.forEach(s-> System.out.print(s+","));
            System.out.println();
        });
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        if(nums == null){
            return null;
        }
        int n = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        if(n < 3){
            return result;
        }
        Arrays.sort(nums);
        for(int i = 0;i < n-2; i++){
            if(nums[i] > 0){
                break;
            }
            if(i > 0 && nums[i-1] == nums[i]){
                continue;
            }
            int j = i+1;
            int k = n-1;
            while(j < k){
                if(nums[i] + nums[j] + nums[k] == 0){
                    List<Integer> tmp = Arrays.asList(nums[i],nums[j],nums[k]);
                    result.add(tmp);
                    while(j < k && nums[j] == nums[j+1]){
                        j++;
                    }
                    while(j < k && nums[k] == nums[k-1]){
                        k--;
                    }
                    j++;
                    k--;
                }
                if(j < k && nums[i] + nums[j] + nums[k] < 0){
                    j++;
                }
                if(j < k && nums[i] + nums[j] + nums[k] > 0){
                    k--;
                }
            }
        }
        return result;
    }
}
